package com.yugao.fintech.draper.core.interceptor;

import com.yugao.fintech.draper.core.enums.HttpConstant;
import com.yugao.fintech.draper.core.model.ResultVO;
import com.yugao.fintech.draper.core.util.WebUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Base64Utils;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 拦截器只放行通过网关的请求
 */
public class ArtServerProtectInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        // 从请求头中获取 gateway Token
        String token = request.getHeader(HttpConstant.GATEWAY_TOKEN_HEADER);
        String gatewayToken = new String(Base64Utils.encode(HttpConstant.GATEWAY_TOKEN_VALUE.getBytes()));
        // 校验 gateway Token的正确性
        if (StringUtils.equals(gatewayToken, token)) {
            return true;
        }
        WebUtil.makeFailureResponse(response, ResultVO.error("Please get resources through the gateway!"));
        return false;
    }
}
